package com.yisu.expressway.driver_revelation.activity;

import android.databinding.DataBindingUtil;
import android.graphics.drawable.AnimationDrawable;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.reflect.TypeToken;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.animation.ValueAnimator;
import com.yisu.expressway.R;
import com.yisu.expressway.activity.BaseActivity;
import com.yisu.expressway.databinding.ActivityRevelationBinding;
import com.yisu.expressway.databinding.RevelationTopicListItemBinding;
import com.yisu.expressway.driver_revelation.model.LiveListItemObj;
import com.yisu.expressway.driver_revelation.model.LiveListObj;
import com.yisu.expressway.listener.onClickHandler;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.ui.recyclerview.BaseRvAdapter;
import com.yisu.expressway.ui.recyclerview.DividerListItemDecoration;
import com.yisu.expressway.ui.recyclerview.PagingRecyclerView;
import com.yisu.expressway.ui.refresh.SuperSwipeRefreshLayout;
import com.yisu.expressway.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class RevelationActivity extends BaseActivity implements SuperSwipeRefreshLayout.OnPullRefreshListener,PagingRecyclerView.SampleActionListener {

    ActivityRevelationBinding binding;

    private ImageView carImage;
    private AnimationDrawable mAnimation;
    private boolean isFreshEnable;

    public static final String NEW_LIVE_POST = "new_live_post";
    private ObjectAnimator floatButtonAnim;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_revelation);
        initView();
        EventBus.getDefault().register(this);
    }

    private void initView(){
        setTitle(R.string.driver_tip_off);
        binding.refreshLayout.setOnPullRefreshListener(this);
        binding.refreshLayout.setHeaderViewBackgroundColor(0xffefeff4);
        binding.refreshLayout.setHeaderView(createHeaderView());
        binding.refreshLayout.setTargetScrollWithLayout(true);
        binding.rvContent.setLayoutManager(new LinearLayoutManager(this));
        binding.rvContent.addItemDecoration(new DividerListItemDecoration(this,LinearLayoutManager.VERTICAL,4));
        showLoading();
        binding.rvContent.init(this,20);
        onHandleListScroll();
    }

    @Subscribe
    public void onReceiverNewLivePostEvent(String newLivePost){
        if(newLivePost.equals(NEW_LIVE_POST)) {
            binding.rvContent.refreshData();
        }
    }

    private View createHeaderView() {
        View headerView = LayoutInflater.from(this)
                .inflate(R.layout.layout_head, null);
        carImage = (ImageView) headerView.findViewById(R.id.pb_view);
        return headerView;
    }

    public void createNewLive(View view){
        startTargetActivity(CreateLiveActivity.class);
    }

    @Override
    public void onRefresh() {
        if(mAnimation != null) {
            mAnimation.start();
        }
        binding.rvContent.refreshData();
    }

    @Override
    public void onPullDistance(int distance) {
        int index = distance / 25;

        int resId = R.drawable.car_1;
        switch (index){
            case 2:
                resId = R.drawable.car_2;
                break;
            case 3:
                resId = R.drawable.car_3;
                break;
            case 4:
                resId = R.drawable.car_4;
                break;
            case 5:
                resId = R.drawable.car_5;
                break;
            case 6:
                resId = R.drawable.car_6;
                break;
            case 7:
                resId = R.drawable.car_7;
                break;
            case 8 :
                resId = R.drawable.car_8;
                break;
            case 9:
                resId = R.drawable.car_9;
                break;
            case 10 :
                resId = R.drawable.car_10;
                break;
        }

        if(!isFreshEnable) {
            carImage.setBackgroundResource(resId);
        }
    }

    @Override
    public void onPullEnable(boolean enable) {
        isFreshEnable = enable;
        if(enable) {
            carImage.setBackgroundResource(R.color.colorTransparent);
            carImage.setImageResource(R.drawable.car_frame);
            mAnimation = (AnimationDrawable) carImage.getDrawable();
        }
    }

    @Override
    public void fetchData(int start, int pageSize) {
        getLiveList(start,pageSize);
    }

    @Override
    public BaseRvAdapter.SampleViewHolder createItemViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.revelation_topic_list_item, parent, false);
        return new LiveHolder(itemView);
    }

    @Override
    public void bindData(BaseRvAdapter.SampleViewHolder _holder, int position, Object _item) {
        LiveHolder holder = (LiveHolder)_holder;
        LiveListObj item = (LiveListObj)_item;

        holder.bind(item,position);
    }

    public  class LiveHolder extends BaseRvAdapter.SampleViewHolder implements onClickHandler {

        private RevelationTopicListItemBinding itemBinding;

        public LiveHolder(View view){
            super(view);
            itemBinding = DataBindingUtil.bind(view);
        }

        public void bind(@NonNull LiveListObj listItem,int position){
            itemBinding.setLiveItem(listItem);
            itemBinding.setClickListener(this);
            itemBinding.setItemPos(position);
        }

        @Override
        public void handleClick(View view) {
            RevelationRoomActivity.launch(RevelationActivity.this,itemBinding.getLiveItem(),itemBinding.ivCover);
        }
    }

    private void getLiveList(int offset,int limit){
        int pageNumber = offset / limit + 1;

        Map<String, Object> params = new HashMap();
        params.put("pageindex",pageNumber);
        params.put("pagesize",limit);

        ApiClientHelper.postApi(ApiSetting.getLiveList(), new TypeToken<LiveListItemObj>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<LiveListItemObj>>() {
            @Override
            public void onResponse(ApiResult<LiveListItemObj> result) {

                stopRefreshAnimation();
                dismissLoading();

                if (!result.success) {
                    ToastUtil.displayShortToastMsg(result.getMsg());
                    binding.rvContent.dataFetchDone(null);
                    return;
                }

                LiveListItemObj itemObj = result.getResult();
                if(itemObj != null){
                    binding.rvContent.dataFetchDone(itemObj.getRidersBrokeNewsVos());
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.displayShortToastMsg(volleyError.getMessage());
                binding.rvContent.dataFetchDone(null);
                dismissLoading();
                stopRefreshAnimation();
            }
        }, this);
    }

    private void stopRefreshAnimation(){
        if(mAnimation != null && mAnimation.isRunning()) {
            binding.refreshLayout.setRefreshing(false);
            mAnimation.stop();
            carImage.setImageResource(R.color.colorTransparent);
        }
    }

    private void onHandleListScroll(){
        binding.rvContent.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState){
                    case RecyclerView.SCROLL_STATE_IDLE:
                        floatButtonAnimation(true);
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        floatButtonAnimation(false);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    private void floatButtonAnimation(final boolean show){

        float startL = show ? 0.0f : 1.0f ;
        float endL = show ? 1.0f : 0.0f ;

        floatButtonAnim = ObjectAnimator
                .ofFloat(binding.ivCreateLive, "IconAnimation", startL,  endL)
                .setDuration(300);

        floatButtonAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
        {
            @Override
            public void onAnimationUpdate(ValueAnimator animation)
            {
                float cVal = (Float) animation.getAnimatedValue();
                binding.ivCreateLive.setAlpha(cVal);
                binding.ivCreateLive.setScaleX(cVal);
                binding.ivCreateLive.setScaleY(cVal);
            }
        });

        floatButtonAnim.addListener(new ValueAnimator.AnimatorListener(){

            @Override
            public void onAnimationStart(Animator animator) {
                if(show){
                    binding.ivCreateLive.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                if(!show){
                    binding.ivCreateLive.setVisibility(View.GONE);
                }else {
                    binding.ivCreateLive.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });

        floatButtonAnim.start();
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
